#ifndef _SERVER_H_
#define _SERVER_H_

#include "logic.h"
#include "wa_exception.h"

class Server:public LogicServer{
public:
    Server(const char* conf):LogicServer(conf){}
    //Server(const char* dbip, int dbport, int port):LogicServer(dbip, dbport, port){}
    void main_handle(MongoClient& client, const WAMessage* msg);
private:
        int getRequestType(const char* request);

        inline DBInterface* getInterface(MongoClient& client, string token){
            std::map<string, DBInterface*>::iterator iter = m_proj_map.find(token);
            if(iter == m_proj_map.end()){
                DBInterface* dbi = new DBInterface(client, token);
                if(dbi != NULL){
                    m_proj_map[token] = dbi;
                    return dbi;
                }
                else{
                    throw WAException("new DBInterface Error", WA_ERR_LEVEL_PRIVATE);
                }
            }
            return iter->second;
        }

        inline bool delInterface(string token){
            std::map<string, DBInterface*>::iterator iter = m_proj_map.find(token);
            if(iter!= m_proj_map.end()){
                delete iter->second;
                m_proj_map.erase(iter);
                return true;
            }
            return false;
        }

        inline void send_result(int fd, BSONObj result){
            BSONObj obj = BSON("error"<<"ok"<<"version"<<m_version<<"result"<<result);
            string rv_str = obj.jsonString();
            send(fd, rv_str.c_str(), rv_str.length(), 0);     
        }
        inline void send_error(int fd, string error){
            string rv_str = BSON("error"<<error<<"version"<<m_version).jsonString();
            send(fd, rv_str.c_str(), rv_str.length(), 0);     
        }
        inline void send_ok(int fd){
            string rv_str = BSON("error"<<"ok"<<"version"<<m_version).jsonString();
            send(fd, rv_str.c_str(), rv_str.length(), 0);     
        }

        std::map<string, DBInterface*> m_proj_map;  // project封装
};

#endif
